<template>
  <div class="details-container">
    <el-row :gutter="20">
      <el-col :span="20">
        <el-form ref="form" label-width="160px" :model="form" :rules="rules">
          <!-- 护肤前 -->
          <!-- {{ form.beforeRules[0].text }} -->
          <el-form-item
            v-for="(item, index) in form.beforeRules"
            :key="`beforeRules-${index}`"
            :label="`护肤前-${item.value}`"
            :prop="`beforeRules.${index}.text`"
            :rules="beforeRulesRules"
          >
            <el-input v-model.trim="item.text" autocomplete="off" type="textarea" />
          </el-form-item>

          <!-- 护肤前衔接语 -->
          <el-form-item label="护肤前衔接语">
            <el-input v-model.trim="form.middleText" autocomplete="off" type="textarea" />
          </el-form-item>

          <!-- 护肤后 -->
          <el-form-item
            v-for="(item, index) in form.afterRules"
            :key="`afterRules-${index}`"
            :label="`护肤后-${item.value}`"
            :prop="`afterRules.${index}.text`"
            :rules="afterRulesRules"
          >
            <el-input v-model.trim="item.text" autocomplete="off" type="textarea" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="save('form')">确定修改</el-button>
            <el-button @click="close('form')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { doEdit } from '@/api/configration'
  import { mapGetters } from 'vuex'
  export default {
    name: 'StrategyDetails',
    data() {
      return {
        form: {
          title: '',
          author: '',
          afterRules: [],
          beforeRules: [],
          list: {},
        },
        data: {},
        apiList: [],
        beforeRulesRules: [{ required: true, trigger: 'blur', message: '请输入护肤前内容' }],
        afterRulesRules: [{ required: true, trigger: 'blur', message: '请输入护肤后内容' }],

        rules: {
          // middleText: [{ required: true, trigger: 'blur', message: '请输入作者' }],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    computed: {
      ...mapGetters({
        visitedRoutes: 'tabsBar/visitedRoutes',
        routes: 'routes/routes',
      }),
    },
    created() {
      console.log(this.$store, 'created', this.$route.query)
    },
    onLoad() {},
    mounted() {
      this.getForm()
    },
    methods: {
      getFormByApiList(targetIndex, indexsIndex) {
        if (this.apiList && Array.isArray(this.apiList)) {
          let target = this.apiList[targetIndex]
          if (target && typeof target === 'object' && target.index && Array.isArray(target.index)) {
            let indexs = target.index[indexsIndex]
            if (indexs && typeof indexs === 'object') {
              let obj = { name: target.target, ...indexs }
              this.form = Object.assign({}, obj)
            }
          }
        }
      },
      setRules() {
        if (this.form && typeof this.form === 'object') {
          Object.keys(this.form).map((item) => {
            console.log('setRules', item, this.rules)
            if (item === 'afterRules' || item === 'beforeRules') {
              this.form[item].map((it, index) => {
                let key = `${item}-${index}`
                this.rules[key] = [{ required: true, trigger: 'blur', message: '请输入内容' }]
              })
            }
          })
        }
      },
      getForm() {
        console.log(this.$store, '参数', this.$route, this.$route.query)

        this.data = this.$store.getters['config/strategyRow']
        this.apiList = this.$store.getters['config/strategyList']
        let { targetIndex, indexsIndex } = this.$route.query
        if (this.data && typeof this.data === 'object' && this.data.list) {
          this.form = Object.assign({}, this.data.list)
        } else if (targetIndex != null && indexsIndex != null) {
          if (!(this.apiList && Array.isArray(this.apiList) && this.apiList.length > 0)) {
            this.$store
              .dispatch('config/getStrategyList', this.form)
              .then((data) => {
                this.apiList = data
                this.getFormByApiList(targetIndex, indexsIndex)
              })
              .catch((err) => {
                console.log('config/strategyList 报错', err)
              })
          } else {
            this.getFormByApiList(targetIndex, indexsIndex)
          }
        }

        console.log(this.form, 'mounted')
      },
      async close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        console.log('...close', this.visitedRoutes)
        // })
        let view
        this.visitedRoutes.forEach((item, index) => {
          if (this.$route.path == item.path) {
            view = item
          }
        })
        this.$router.push({ path: '/copywriting/strategy/index' })
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.apiList && this.form && Array.isArray(this.apiList)) {
              let { targetIndex, indexsIndex } = this.$route.query
              if (targetIndex != null && indexsIndex != null) {
                let target = this.apiList[targetIndex]
                if (
                  target &&
                  typeof target === 'object' &&
                  target.index &&
                  Array.isArray(target.index)
                ) {
                  let indexs = target.index[indexsIndex]
                  console.log(this.form, '...修改', indexs)
                  if (indexs && typeof indexs === 'object') {
                    target.index[indexsIndex] = this.form
                  }
                }
              }
            }
            console.log(this.form, '...修改...', this.apiList)

            const props = {
              configValue: this.apiList,
              configItem: 'Strategy',
            }
            let { data, error } = await doEdit(props).catch((err) => {
              console.log('err')
              this.$baseMessage('接口报错', 'error')
            })
            if (!error) {
              this.$baseMessage('操作成功', 'success')
              this.close()
            } else {
              this.$baseMessage(error || '接口报错', 'error')
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
